<template>
	<div>
		<el-row :gutter="20">
			<el-col :span="6">
				<el-input placeholder="请输入内容" v-model="listQuery.name" clearable></el-input>
			</el-col>

			<el-col :span="8" style="padding: 0">
				<el-button type="custom" plain @click="getList({ page: 1 })">搜索</el-button>
				<el-button type="custom" @click="showEditDialog('add')" v-if="$button('115')">新增</el-button>
			</el-col>
		</el-row>

		<!-- <el-menu
        class="el-menu-demo"
        mode="horizontal"
        :default-active="listQuery.king"
        background-color="#ffffff"
        @select="handleClick"
      >
        <el-menu-item index="1">菜单角色</el-menu-item>
        <el-menu-item index="2">权限角色</el-menu-item> 
        </el-menu>-->

		<el-table :data="roleTableData" style="width: 100%" max-height="600" stripe>
			<el-table-column fixed prop="name" label="角色名称" show-overflow-tooltip></el-table-column>
			<el-table-column prop="userType" label="角色类型" width="140px">
				<template slot-scope="{ row }">
					<span>{{ userTypeFilter(row.userType) }}</span>
				</template>
			</el-table-column>
			<el-table-column fixed prop="dataScope" label="数据权限等级" show-overflow-tooltip>
				<template slot-scope="{ row }">
					<span v-if="row.dataScope">
						{{ getDedaScope(row.dataScope) }}
						<span>({{ row.dataScope }})</span>
					</span>
					<p v-else>--</p>
				</template>
			</el-table-column>
			<el-table-column prop="content" label="备注" show-overflow-tooltip></el-table-column>
			<!-- <el-table-column
        prop="createName"
        label="创建人"
        width="140px"
      ></el-table-column> -->
			<el-table-column prop="createTime" label="创建时间" width="180px"></el-table-column>
			<!-- <el-table-column prop="updateTime" label="修改时间" width="180px"></el-table-column> -->
			<el-table-column label="操作" width="220px">
				<template slot-scope="{ row }">
					<el-button-group>
						<el-button
							type="warning"
							size="mini"
							class="jurisdiction"
							@click="jurisdiction(row)"
							:disabled="$button('116') == false ? true : false"
						>
							菜单权限
						</el-button>
						<!--   <el-button
              type="success"
              size="mini"
              class="jurisdiction"
              @click="jurisdiction(row,'data')"
              >数据权限</el-button
            >
            <el-button
                type="success"
                size="mini"
                class="jurisdiction"
                @click="personnelShow(row)"
            
                >选择人员</el-button
                        >-->
						<el-button
							type="primary"
							size="mini"
							:disabled="$button('117') == false ? true : false"
							@click="showEditDialog('edit', row)"
							class="jurisdiction"
						>
							编辑
						</el-button>
						<el-button type="danger" size="mini" class="jurisdiction" :disabled="$button('118') == false ? true : false" @click="delrole(row)">
							删除
						</el-button>
					</el-button-group>
				</template>
			</el-table-column>
		</el-table>

		<Pagination
			style="margin-top: 20px"
			v-show="parseInt(pageObj.count) > 0"
			:total="parseInt(pageObj.count)"
			@change="getList"
			:page.sync="listQuery.page"
			:limit.sync="listQuery.limit"
		/>

		<!-- 角色管理-新增/编辑 -->
		<el-dialog
			:title="addOrEdit ? '角色管理-新增' : '角色管理-编辑'"
			:visible.sync="dialogFormVisible"
			width="600px"
			:close-on-click-modal="false"
			@close="$reset('temp')"
		>
			<el-form ref="temp" :model="temp" :rules="rules" label-width="120px">
				<el-form-item label="角色名称" prop="name">
					<el-input v-model="temp.name"></el-input>
				</el-form-item>
				<el-form-item label="角色类型" prop="userType">
					<el-select v-model="temp.userType" filterable placeholder="请选择角色类型">
						<el-option v-for="v in userTypeData" :key="v.id" :label="v.deName" :value="v.deValue"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="数据权限等级" prop="dataScope">
					<el-select v-model="temp.dataScope" filterable placeholder="请选择数据权限等级">
						<el-option label="低权 - 仅自己" value="1"></el-option>
						<el-option label="中低权 - 本部门" value="3"></el-option>
						<el-option label="中权 - 本部门及以下" value="5"></el-option>
						<el-option label="中高权 - 自定义" value="7"></el-option>
						<el-option label="高权 - 所有" value="9"></el-option>
					</el-select>

					<!-- <el-tooltip placement="top">
            <div slot="content">
              1:低权 - 仅自己
              <br />3:中低权 - 本部门 <br />5:中权 - 本部门及以下 <br />7:中高权
              - 自定义 <br />9:高权 - 所有
            </div>
            <i class="el-icon-question" style="margin-left: 10px"></i>
          </el-tooltip> -->
				</el-form-item>
				<el-form-item label="权限部门" v-if="temp.dataScope == 7">
					<div class="depwrap">
						<el-tree
							:data="companyTableData"
							show-checkbox
							node-key="id"
							:props="defaultProps"
							:expand-on-click-node="false"
							:default-expand-all="false"
							:check-strictly="false"
							ref="deptree"
							accordion
							:default-checked-keys="checkedIds"
							:default-expanded-keys="loadIds"
						>
							<span class="custom-tree-node" slot-scope="{ data }">
								<span>{{ data.name }}</span>
							</span>
						</el-tree>
					</div>
				</el-form-item>
				<!-- <el-form-item label="角色类型" prop="type">
          <template>
            <el-radio v-model="temp.type" label="1">菜单角色</el-radio>
            <el-radio v-model="temp.type" label="2">权限角色</el-radio>
          </template> 
                </el-form-item>-->
				<!-- <el-form-item label="资源等级" prop="type">
          <el-select style="width:100%" v-model="temp.type" placeholder="请选择等级">
            <el-option value="1" label="一级"></el-option>
            <el-option value="2" label="二级"></el-option>
            <el-option value="3" label="三级"></el-option>
            <el-option value="4" label="四级"></el-option>
          </el-select>
                </el-form-item>-->
				<el-form-item label="备注">
					<el-input type="textarea" v-model="temp.content" maxlength="50" show-word-limit></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button v-show="!addOrEdit" type="custom" v-preventReClick @click="handleUpdate()">提 交</el-button>
				<el-button v-show="addOrEdit" type="custom" v-preventReClick @click="handleAdd('temp')">新 增</el-button>
				<el-button @click="dialogFormVisible = false">取 消</el-button>
			</div>
		</el-dialog>

		<!-- 权限配置 -->
		<el-dialog title="权限配置" :visible.sync="showJurisdiction" width="700px" :close-on-click-modal="false">
			<el-form :rules="rules" label-width="80px">
				<el-form-item label="菜单" class="dataJurisdiction_tree">
					<el-tree
						:data="dataJurisdiction"
						show-checkbox
						node-key="id"
						:expand-on-click-node="false"
						:default-expand-all="false"
						:check-strictly="isStrictly"
						ref="tree"
						accordion
						:default-checked-keys="checkedIds"
						:default-expanded-keys="loadIds"
					>
						<span class="custom-tree-node" slot-scope="{ data }">
							<span>{{ data.name }}</span>
						</span>
					</el-tree>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="custom" v-preventReClick @click="submitJurisdiction()">提 交</el-button>
				<el-button @click="showJurisdiction = false">取 消</el-button>
			</div>
		</el-dialog>
		<!-- 选择人员 -->
		<el-dialog title="选择人员" :visible.sync="showPersonnel" width="700px" :close-on-click-modal="false">
			<el-form :rules="rules" label-width="80px">
				<el-menu class="el-menu-demo" mode="horizontal" :default-active="listQuery.king" background-color="#ffffff" @select="personnelHandleClick">
					<el-menu-item index="1">选择人员</el-menu-item>
					<el-menu-item index="2">选择部门</el-menu-item>
				</el-menu>

				<el-card class="box-card mb15" v-show="personnelTabs == 1">
					<el-checkbox label="张三"></el-checkbox>
				</el-card>
				<el-card class="box-card mb15" v-show="personnelTabs == 2"></el-card>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="custom" v-preventReClick @click="showPersonnel()">提 交</el-button>
				<el-button @click="showPersonnel = false">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script>
import { getSession, setSession } from '@/utils/session';
import { tbRoleAdd, tbRoleQuery, tbRoleUpdate, tbRoleDelete, tbSysRoleMenuAddBatch } from '@/api/admin/system/role';
import { tbDeptQuery } from '@/api/admin/system/unitManage.js';
import { tbMenuQueryData, tbMenuTree } from '@/api/admin/system/menu';
export default {
	created() {
		this.getList();
		this.getTbDeptQuery();
	},
	data() {
		return {
			temp: {
				type: '1'
			},
			live: '',
			tabs: 1,
			personnelTabs: 1,
			roleTableData: [],
			listQuery: {
				page: 1,
				limit: 10,
				name: '',
				type: '1',
				king: '1',
				userType: ''
			},
			dialogFormVisible: false,
			showJurisdiction: false,
			showPersonnel: false,
			dataJurisdiction: [],
			pageObj: {},
			addOrEdit: true,
			checkedIds: [], //默认选中的菜单ID
			loadIds: [], //默认展开的菜单ID
			rules: {
				name: [
					{
						required: true,
						message: '请输入角色名称',
						trigger: 'blur'
					}
				],
				dataScope: [
					{
						required: true,
						message: '请选择数据权限等级',
						trigger: 'blur'
					}
				],
				userType: [
					{
						required: true,
						message: '请选择角色类型',
						trigger: 'change'
					}
				]
			},
			showDataPermission: false,
			listQueryData: {
				pId: '0'
			},
			companyTableData: [],
			defaultProps: {
				children: 'childList',
				label: 'name'
			},
			isStrictly: true,
			aRR: []
		};
	},
	props: ['userTypeData'],
	computed: {
		userTypeFilter() {
			return (val) => {
				let name = this.userTypeData
					.filter((v) => v.deValue == val)
					.map((v) => v.deName)
					.toString();
				return name || '--';
			};
		}
	},
	mounted() {
		this.$bus.$on('refreshRoleList', this.getList);
	},
	beforeDestroy() {
		this.$bus.$off('refreshRoleList');
	},
	methods: {
		//获取列表
		getList(data) {
			if (data) {
				Object.assign(this.listQuery, data);
			} else {
				this.listQuery.userType = '';
			}
			if (this.tabs == 1) {
				this.listQuery.type = '1';
			} else if (this.tabs == 2) {
				this.listQuery.type = '2';
			}
			tbRoleQuery(this.listQuery).then((res) => {
				this.roleTableData = res.data.data;
				this.pageObj = res.data;
			});
		},
		//菜单角色和权限角色切换
		handleClick(tab) {
			this.tabs = tab;
			this.getList();
		},
		//选择人员里面部门和人员切换
		personnelHandleClick(tab) {
			this.personnelTabs = tab;
		},
		//人员选择弹出框显示
		personnelShow(row) {
			this.showPersonnel = true;
		},
		//删除
		delrole: function (row) {
			const loading = this.$loading(this.openLoading);
			this.temp = { ...row };
			this.$confirm('删除角色将严重影响平台功能, 是否删除?', '提示', {
				confirmButtonText: '删除',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					tbRoleDelete(this.temp.id).then((res) => {
						if (res.data.code == 0) {
							this.$message.success(res.data.msg);
						} else {
							this.$message.error(res.data.msg);
						}
						this.getList();
						loading.close();
					});
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
					loading.close();
				});
		},
		// 获取部门列表
		getTbDeptQuery() {
			tbDeptQuery(this.listQueryData).then((res) => {
				this.companyTableData = res.data.data;
			});
		},
		//新增/编辑弹框
		showEditDialog(type, row) {
			if (type == 'add') {
				this.addOrEdit = true;
			} else {
				this.addOrEdit = false;
			}

			this.temp = { ...row };
			// str.split(",");
			var depArr = [];
			if (this.temp.depts) {
				depArr = this.temp.depts.split(',');
			}
			this.checkedIds = depArr;

			this.dialogFormVisible = true;
		},
		//新增
		handleAdd(temp) {
			if (this.temp.dataScope == undefined || this.temp.dataScope == '') {
				this.temp.depts = '';
			} else {
				if (this.temp.dataScope == 7) {
					var deptree = this.$refs.deptree.getCheckedKeys();
					if (deptree.length > 0) {
						this.temp.depts = deptree.join(',');
					} else {
						this.$message.error('数据权限等级为7必须选择部门');
						return false;
					}
				}
			}
			this.$refs[temp].validate((valid) => {
				if (valid) {
					this.temp.type = 1;
					tbRoleAdd(this.temp).then((res) => {
						if (res.data.code == 0) {
							this.$message.success(res.data.msg);
						} else {
							this.$message.error(res.data.msg);
						}
						this.dialogFormVisible = false;
						this.getList();
					});
				}
			});
		},
		//编辑
		handleUpdate() {
			// const loading = this.openLoading();
			this.temp.type = 1;

			if (this.temp.dataScope == undefined || this.temp.dataScope == '') {
				this.temp.depts = '';
			} else {
				if (this.temp.dataScope == 7) {
					var deptree = this.$refs.deptree.getCheckedKeys();
					if (deptree.length > 0) {
						this.temp.depts = deptree.join(',');
					} else {
						this.$message.error('数据权限等级为7必须选择部门');
						return false;
					}
				}
			}

			tbRoleUpdate(this.temp).then((res) => {
				if (res.data.code == 0) {
					this.$message.success(res.data.msg);
				} else {
					this.$message.error(res.data.msg);
				}
				this.dialogFormVisible = false;
				this.getList();
				loading.close();
				// location.reload();
			});
		},
		//配置权限
		jurisdiction(row, type) {
			this.temp = { ...row };
			var userinfo = JSON.parse(getSession('userinfo'));

			if (userinfo == null) {
				this.$message.success('请登录！');
				this.$router.push('./login');
				return;
			}
			//获取菜单列表
			tbMenuQueryData({ pId: 0 }).then((res) => {
				if (res.data.code == 0) {
					if (type == 'data') {
						this.showDataPermission = true;
					} else {
						this.showDataPermission = false;
					}
					this.showJurisdiction = true;

					var data = res.data.data;
					if (userinfo.id != -1) {
						data.forEach((e) => {
							if (e.id == 16) {
								e.childList.forEach((k, index) => {
									if (k.id == 47) {
										e.childList.splice(index, 1);
									}
								});
							}
						});
					}
					this.dataJurisdiction = res.data.data;
					this.dataJurisdiction.forEach((item, index, arr) => {
						this.dataJurisdiction[index].children = this.dataJurisdiction[index].childList;
						this.dataJurisdiction[index].children.forEach((item2, index2, arr2) => {
							this.dataJurisdiction[index].children[index2].children = this.dataJurisdiction[index].childList[index2].childList;
						});
					});
				}
			});
			//获取已选菜单列表
			this.isStrictly = true;
			tbMenuTree(this.temp.id).then((res) => {
				if (res.data.code == 0) {
					let data = res.data.data;
					this.checkedIds = [];
					this.aRR = [];
					this.calleArr(data);

					this.$nextTick(() => {
						this.checkedIds = this.aRR;
						setTimeout(() => {
							this.isStrictly = false;
						}, 1000);
						//  this.isStrictly=false;
					});
				}
			});
		},
		calleArr(array) {
			for (let i in array) {
				var data = array[i];
				if (data.childList) {
					if (data.checked) {
						this.aRR.push(data.id);
						this.calleArr(data.childList); //自己调用自己
					} else {
						this.calleArr(data.childList); //自己调用自己
					}
				} else {
					if (data.checked) {
						this.aRR.push(data.id);
					} else {
						this.calleArr(data.childList); //自己调用自己
					}
				}
			}
		},
		//配置权限提交
		submitJurisdiction() {
			var configPer = this.$refs.tree.getCheckedKeys();
			var configPer2 = this.$refs.tree.getHalfCheckedNodes();

			let parms = [];
			for (let arr in configPer) {
				parms.push({ roleId: this.temp.id, menuId: configPer[arr] });
			}
			for (let arr2 in configPer2) {
				parms.push({
					roleId: this.temp.id,
					menuId: configPer2[arr2].id
				});
			}

			tbSysRoleMenuAddBatch(parms).then((res) => {
				if (res.data.code == 0) {
					this.$message.success(res.data.msg);
					this.showJurisdiction = false;
				} else {
					this.$message.error(res.data.msg);
				}
			});
			this.showJurisdiction = false;
		},
		// 数据权限
		setDataPermission() {
			this.showDataPermission = true;
		},
		getDedaScope(type) {
			var name = '';
			if (type == 1) {
				name = '低权-仅自己';
			}
			if (type == 3) {
				name = '中低权-本部门';
			}
			if (type == 5) {
				name = '中权-本部门及以下';
			}
			if (type == 7) {
				name = '中高权-自定义部门';
			}
			if (type == 9) {
				name = '高权-所有';
			}
			return name;
		}
	}
};
</script>

<style scoped>
.left-menu {
	display: block;
}
.depwrap {
	border: 1px solid #dcdfe6;
	padding: 10px;
	max-height: 200px;
	overflow: auto;
	border-radius: 5px;
}
.el-form-item.dataJurisdiction_tree .el-tree {
	height: 450px;
	overflow-y: auto;
	border: 1px solid #dcdfe6;
}
</style>
